/*
 * @Descripttion: 
 * @version: 
 * @Author: ada.wu
 * @Date: 2023-10-29 23:17:25
 * @LastEditors: ada.wu
 * @LastEditTime: 2023-11-04 21:34:59
 */

import { createRouter, createWebHistory } from 'vue-router'
import adminRoutes from './admin';
import { createPinia } from 'pinia'
import useAuthStore from '@/stores/useAuthStore';
import useUserStore from '@/stores/useUserStore';


import {ElMessage } from 'element-plus';
import userRoutes from "@/router/user";

const authStore = useAuthStore(createPinia());




const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/index/index'
    },
    {
      path: '/login',
      component: () => import('../views/login/LoginView.vue')
    },
    {
      path: '/404',
      component: () => import("../views/error/E404View.vue")
    },
    // {
    //   path: "/:catchAll(.*)", // 不识别的path自动匹配404
    //   redirect: '/404',
    // },

    {
      path: '/home',
      component: () => import('../views/home/HomeView.vue')
    },
    {
      path: '/user/home',
      component: () => import('../views/home/HomeView.vue'),
      meta: { title: "角色管理", needLogin: true ,user:true },
    },
    {
      name: '/admin',
      component: () => import('../views/layouts/BaseLayoutView.vue'),
      meta: { needLogin: true },
      children: [
        // {
        //   path: '/index/index',
        //   component: () => import('../views/index/IndexView.vue'),
        //   meta: { needLogin: true },
        // },
        ...adminRoutes,
        {
          path: '/admin/404',
          component: () => import("../views/error/E404View.vue")
        },
      ]
    },
    {
      name: '/user',
      component: () => import('../views/layouts/BaseLayoutView.vue'),
      meta: { needLogin: true },
      children: [
        // {
        //   path: '/index/index',
        //   component: () => import('../views/index/IndexView.vue'),
        //   meta: { needLogin: true },
        // },
        ...userRoutes,
        {
          path: '/admin/404',
          component: () => import("../views/error/E404View.vue")
        },
      ]
    }
  ]
})

// 全局路由前置守卫 - 检查用户登录状态
// [vue3动态路由的实现](https://blog.csdn.net/csdnyp/article/details/125558980)
// [Vue3动态添加路由及生成菜单](https://www.cnblogs.com/nmgwap/p/16331607.html)
// [vue3 使用addRoute动态添加路由](https://www.luweipai.cn/html/1646221364/)
router.beforeEach((to) => {
  console.log('[INFO] 路由文件 - 路由守卫信息', to, router);
  if (to.matched.length == 0) {
    return { path: '/admin/404' };
  }
  if (to.meta.needLogin && !authStore.getToken()) {
    console.log('[INFO] 路由文件 - 路由守卫信息 未登录');
    return { path: '/login' };
  }
  const useStore = useUserStore();
  if(to.meta.hasOwnProperty('isSupper') && to.meta.isSupper != useStore.user.isSupper){
    ElMessage.warning("无访问权限")
    return {path:'/home'}
  }
})
export default router
